package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelCommendQuery;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelCommendService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.domain.DestinationTemplate;
import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.domain.TravelTemplate;
import cn.wolfcode.luowowo.search.domain.UserInfoTemplate;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.*;
import cn.wolfcode.luowowo.search.vo.SearchResultVO;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelTemplateSearchService travelTemplateSearchService;

    @Reference
    private ITravelCommendService travelCommendService;

    @Reference
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IStrategyCommendService strategyCommendService;

    @Reference
    private ITravelService travelService;

    @Reference
    private ISearchService searchService;

    @Reference
    private IDestinationTemplateSearchService destinationTemplateSearchService;

    @Reference
    private IStrategyTemplateSearchService strategyTemplateSearchService;

    @Reference
    private IUserInfoTemplateSearchService userInfoTemplateSearchService;

    // 访问 http://localhost:8888/
    @RequestMapping("") // 注意：此处不能写 @RequestMapping("/")，会把所有路径都做匹配
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){
        // 从 cookie 中拿到 token
        String token = CookieUtil.getCookie(request); // 4322323312232334
        if(token != null){
            UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
            if(userInfo != null){
                // 延长 cookie 和 redis 的 token 时间
                CookieUtil.addCookie("token", token, RedisKeys.TOKEN_CODE.getTime(), response);
                userInfoRedisService.expire(RedisKeys.TOKEN_CODE.join(token), RedisKeys.TOKEN_CODE.getTime());
                // 把用户信息通过 session 共享到页面 -- 这个地方还要在拦截器再写一次，防止如果用户不去访问主页，就不能拿到 session
                request.getSession().setAttribute("userInfo", userInfo);
            }
        }

        // tcs
        model.addAttribute("tcs", travelCommendService.getTop5());

        // sc
        model.addAttribute("sc", strategyCommendService.getTop5().get(0));

        return "index/index";
    }

    @RequestMapping("index/travelPage")
    public String travelPage(Model model, @ModelAttribute("qo") TravelQuery qo){

        //pageInfo
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        return "index/travelPageTpl";

    }

    @RequestMapping("q")
    public String search(Model model, @ModelAttribute("qo") SearchQueryObject qo){

        // data
        //条件的类别: 国内(provinceId)  国外(countryId)  主题(themeid)
        // 全部搜索， 会对目的地， 攻略， 游记， 用户对象(关键字段)进行全文搜索
        //目的地： 名称(name), 简介(info)
        //攻略： 标题(title), 副标题(subTitle), 概要(summary)
        //游记：标题(title), 概要(summary)
        //用户： 昵称(nickname), 目的地名(destName)

        switch (qo.getType()){
            case SearchQueryObject.SEARCH_TYPE_ALL:
                return searchAll(model, qo);
            case SearchQueryObject.SEARCH_TYPE_DEST:
                return searchDest(model, qo);
            case SearchQueryObject.SEARCH_TYPE_STRATEGY:
                return searchStrategy(model, qo);
            case SearchQueryObject.SEARCH_TYPE_TRAVEL:
                return searchTravel(model, qo);
            default:
                return searchUser(model, qo);
        }
    }

    // 精确查询
    // 输入关键词是精确查询输入的地区， 如果找到， 显示该目的地下所有攻略， 游记， 用户
    private String searchDest(Model model, SearchQueryObject qo) {

        DestinationTemplate dest = destinationTemplateSearchService.findByName(qo.getKeyword());
        SearchResultVO data = new SearchResultVO();
        if(dest != null){

            List<StrategyTemplate>  strategys = strategyTemplateSearchService.findByDestName(dest.getName());

            List<UserInfoTemplate> users = userInfoTemplateSearchService.findByDestName(dest.getName());

            List<TravelTemplate> travels = travelTemplateSearchService.findByDestName(dest.getName());

            data.setStrategys(strategys);
            data.setUsers(users);
            data.setTravels(travels);
            long count = Long.parseLong(strategys.size() + users.size() + travels.size() + "");
            data.setTotal(count);
        }

        model.addAttribute("data", data);
        // dest
        model.addAttribute("dest", dest);

        return "index/searchDest";
    }

    private String searchTravel(Model model, SearchQueryObject qo) {
        model.addAttribute("page", searchService.searchWithHighlight(
                TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary"));
        return "index/searchTravel";
    }

    private String searchStrategy(Model model, SearchQueryObject qo) {
        model.addAttribute("page", searchService.searchWithHighlight(
                StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary"));
        return "index/searchStrategy";
    }

    public String searchUser(Model model, SearchQueryObject qo){
        model.addAttribute("page", searchService.searchWithHighlight(
                UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName"));
        return "index/searchUser";
    }

    // 查询全部
    public String searchAll(Model model, SearchQueryObject qo){
        Page<DestinationTemplate> destinationTemplates = searchService.searchWithHighlight(
            DestinationTemplate.INDEX_NAME, DestinationTemplate.TYPE_NAME,
            DestinationTemplate.class, qo, "name", "info");


        Page<StrategyTemplate> strategyTemplates = searchService.searchWithHighlight(
                StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary");

        Page<TravelTemplate> travelTemplates = searchService.searchWithHighlight(
                TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");

        Page<UserInfoTemplate> userInfoTemplates = searchService.searchWithHighlight(
                UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName");

        SearchResultVO data = new SearchResultVO();
        data.setDests(destinationTemplates.getContent());
        data.setUsers(userInfoTemplates.getContent());
        data.setStrategys(strategyTemplates.getContent());
        data.setTravels(travelTemplates.getContent());
        long total = destinationTemplates.getTotalElements() + travelTemplates.getTotalElements() +
                userInfoTemplates.getTotalElements() + strategyTemplates.getTotalElements();
        data.setTotal(total);
        model.addAttribute("data", data);

        return "index/searchAll";
    }

}
